package com.alibaba.dubbo.common.io;

public class UnsafeChunk {
	private byte []data;
	private int  size;
	
	UnsafeChunk(int size){
		data = new byte[size];
		size = 0;
	}

	public byte[] data() {
		return data;
	}

	public int total(){
		return data.length;
	}
	
	public int size() {
		return size;
	}

	public int available(){
		return this.data.length - size;
	}
	
	public void reset(){
		this.size = 0;
	}
	
	/**
	 * 返回写入的字节数
	 * @param data
	 * @param offset
	 * @param len
	 * @return
	 */
	public int write(byte[]data, int offset, int len){
		if(data == null || data.length == 0 || len == 0) return 0;
		if(offset < 0 || len < 0 || (offset + len) > data.length) throw new java.lang.IndexOutOfBoundsException();
		if(this.data.length <= size) return 0;
		int available = Math.min(this.available(), len);
		System.arraycopy(data, offset, this.data, size, available);
		this.size += available;
		return available;
	}
	
	public int write(byte b){
		if(this.data.length == 0 || size >= this.data.length) return -1;
		this.data[size] = b;
		this.size ++;
		return b;
	}
	
	public void skip(){
		if(this.size > this.data.length) throw new java.lang.IllegalStateException();
		this.size++;
	}
	
	public void skip(int len){
		if(len < 0 || (this.size + len) > this.data.length) throw new java.lang.IllegalStateException();
		this.size += len;
	}
}
